<template>
  <div class="charts">
    <div class="header">
      <div class="title" v-if="config[showIndex]" :title="config[showIndex].title">
        {{ config[showIndex].title }}
      </div>
      <div class="toggle" v-if="config.length > 1" @click="showChart">
        <img
          src="//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/3de158a5-d91d-49bb-9f0d-d34906849810.png"
          alt=""
        />
        <span>换图</span>
      </div>
    </div>
    <div class="chart" ref="chart"></div>
  </div>
</template>

<script>
import draw from '../draws/index';
export default {
  props: {
    /**
     * - line：折线图
     * - dual_line：双Y轴折线图
     * - bar：柱状图
     * - scatter：散点图
     */
    config: {
      type: Array,
      default: () => [],
      required: true
    },
    chartData: { type: Array, default: () => [], required: true }
  },
  data() {
    return {
      showIndex: -1,
      chartInstance: null,
      drawType: null
    };
  },
  methods: {
    showChart() {
      this.showIndex = (this.showIndex + 1) % this.config.length;
      const type = this.config[this.showIndex].chart_type;
      this.$nextTick(() => {
        const { chartIns, type: drawType } = draw({
          dom: this.$refs.chart,
          data: this.chartData,
          chartConfig: this.config[this.showIndex].chart_config,
          type,
          originType: this.drawType,
          originIns: this.chartInstance
        });
        this.chartInstance = chartIns;
        this.drawType = drawType;
      });
    }
  },
  mounted() {
    this.showChart();
  }
};
</script>
<style lang="less" scoped>
.charts {
  width: 100%;
  height: 260px;
  margin-bottom: 12px;
  &:hover {
    .header .toggle {
      display: flex;
    }
  }
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 28px;
    .title {
      font-family: PingFangSC-Regular;
      font-size: 16px;
      color: #e9e9f2;
      line-height: 24px;
      font-weight: 400;
      width: 270px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .toggle {
      display: none;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      width: 66px;
      height: 28px;
      background: rgba(255, 255, 255, 0.06);
      border-radius: 4px;
      img {
        width: 16px;
        height: 16px;
        margin-right: 2px;
      }
      span {
        font-family: PingFangSC-Regular;
        font-size: 13px;
        color: #e9e9f2;
        text-align: center;
        line-height: 16px;
        font-weight: 400;
      }
    }
  }
  .chart {
    width: 100%;
    height: 220px;
    margin-top: 12px;
  }
}
</style>
